<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. Pading ######1). 简介分页库使您可以更轻松地在应用程序的RecyclerView中逐步和优雅地加载数据。许多应用程序使用包含大量项目的数据源中的数据，但一次只显示一小部分。分页库可帮助您的应用观察并显示此数据的合理子集。 此功能有几个优点：数据请求消耗的网络带宽更少，系统资源更少。 拥有计量或小数据计划的用户会欣赏这些具有数据意识的应用程序。即使在数据更新和刷新期间，">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Architecture----Paging">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Android-Jetpack/Architecture----Paging/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. Pading ######1). 简介分页库使您可以更轻松地在应用程序的RecyclerView中逐步和优雅地加载数据。许多应用程序使用包含大量项目的数据源中的数据，但一次只显示一小部分。分页库可帮助您的应用观察并显示此数据的合理子集。 此功能有几个优点：数据请求消耗的网络带宽更少，系统资源更少。 拥有计量或小数据计划的用户会欣赏这些具有数据意识的应用程序。即使在数据更新和刷新期间，">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-08-06T11:12:22.601Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Architecture----Paging">
<meta name="twitter:description" content="####1. Pading ######1). 简介分页库使您可以更轻松地在应用程序的RecyclerView中逐步和优雅地加载数据。许多应用程序使用包含大量项目的数据源中的数据，但一次只显示一小部分。分页库可帮助您的应用观察并显示此数据的合理子集。 此功能有几个优点：数据请求消耗的网络带宽更少，系统资源更少。 拥有计量或小数据计划的用户会欣赏这些具有数据意识的应用程序。即使在数据更新和刷新期间，">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Android-Jetpack/Architecture----Paging/"/>





  <title>Architecture----Paging | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Android-Jetpack/Architecture----Paging/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Architecture----Paging</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. Pading</p>
<p>######1). 简介<br>分页库使您可以更轻松地在应用程序的RecyclerView中逐步和优雅地加载数据。许多应用程序使用包含大量项目的数据源中的数据，但一次只显示一小部分。分页库可帮助您的应用观察并显示此数据的合理子集。 此功能有几个优点：<br>数据请求消耗的网络带宽更少，系统资源更少。 拥有计量或小数据计划的用户会欣赏这些具有数据意识的应用程序。<br>即使在数据更新和刷新期间，应用程序仍会继续快速响应用户输入。</p>
<a id="more"></a>
<p>######2). 依赖<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">ext &#123;</span><br><span class="line">  paging_version = &quot;1.0.0-alpha6&quot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">dependencies &#123;</span><br><span class="line">  // paging</span><br><span class="line">  implementation &quot;android.arch.paging:runtime:$paging_version&quot;</span><br><span class="line">  implementation(&quot;android.arch.paging:rxjava2:1.0.0-rc1&quot;) &#123;</span><br><span class="line">    exclude group: &apos;android.arch.paging&apos;, module: &apos;common&apos;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######3). DataSource</p>
<ul>
<li>PageKeyedDataSource: 如果您加载的页面嵌入了下一个/上一个键，请使用PageKeyedDataSource。 例如，如果您从网络中获取社交媒体帖子，则可能需要将nextPage令牌从一个加载传递到后续加载。</li>
<li>ItemKeyedDataSource: 如果需要使用项目N中的数据来获取项目N + 1，请使用ItemKeyedDataSource。 例如，如果您要为讨论应用程序提取线程注释，则可能需要传递最后一条注释的ID以获取下一条注释的内容。</li>
<li>PositionalDataSource: 如果需要从数据存储中选择的任何位置获取数据页，请使用PositionalDataSource。 此类支持从您选择的任何位置开始请求一组数据项。 例如，请求可能返回以位置1200开头的20个数据项。</li>
</ul>
<p>####2.  Paging + Room</p>
<p>######1). 创建Room数据实体<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Room 实体</span><br><span class="line"> * Created by mazaiting on 2018/7/25.</span><br><span class="line"> */</span><br><span class="line">@Entity(tableName = &quot;student&quot;)</span><br><span class="line">data class StudentRoom(</span><br><span class="line">        var name: String</span><br><span class="line">) &#123;</span><br><span class="line">  @PrimaryKey(autoGenerate = true)</span><br><span class="line">  var id: Int = 0</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######2). 创建数据库DAO<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 数据库操作对象</span><br><span class="line"> * Created by mazaiting on 2018/7/26.</span><br><span class="line"> */</span><br><span class="line">@Dao</span><br><span class="line">interface StudentDao &#123;</span><br><span class="line">  /**</span><br><span class="line">   * 插入数据</span><br><span class="line">   */</span><br><span class="line">  @Insert</span><br><span class="line">  fun insert(student: List&lt;StudentRoom&gt;)</span><br><span class="line">  </span><br><span class="line">  /**</span><br><span class="line">   * 查询所有学生</span><br><span class="line">   */</span><br><span class="line">  @Query(&quot;SELECT * FROM student ORDER BY id DESC&quot;)</span><br><span class="line">  fun findAllStudents() : DataSource.Factory&lt;Int, StudentRoom&gt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######3). 创建数据库<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 数据库</span><br><span class="line"> * Created by mazaiting on 2018/7/26.</span><br><span class="line"> */</span><br><span class="line">@Database(entities = arrayOf(StudentRoom::class), version = 1)</span><br><span class="line">abstract class StudentDatabase : RoomDatabase() &#123;</span><br><span class="line">  // 获取DAO</span><br><span class="line">  abstract fun studentDao() : StudentDao</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######4). 创建ViewModel<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">class StudentViewModel : ViewModel() &#123;</span><br><span class="line">  /**</span><br><span class="line">   * 查询所有学生</span><br><span class="line">   */</span><br><span class="line">  fun findAllStudents(application: Application): LiveData&lt;PagedList&lt;StudentRoom&gt;&gt; &#123;</span><br><span class="line">    val db = Room.databaseBuilder(application, StudentDatabase::class.java, &quot;PAGING&quot;).build()</span><br><span class="line">    val dao = db.studentDao()</span><br><span class="line">//    val list: LiveData&lt;PagedList&lt;StudentRoom&gt;&gt; =</span><br><span class="line">//            LivePagedListBuilder(dao.findAllStudents(), 15).build()</span><br><span class="line">    val list: LiveData&lt;PagedList&lt;StudentRoom&gt;&gt; =</span><br><span class="line">            LivePagedListBuilder(dao.findAllStudents(),</span><br><span class="line">                    PagedList.Config.Builder()</span><br><span class="line">                            // 设置分页加载数量</span><br><span class="line">                            .setPageSize(PAGE_SIZE)</span><br><span class="line">                            // 配置是否启动PlaceHolders</span><br><span class="line">                            .setEnablePlaceholders(ENABLE_PLACE_HOLDERS)</span><br><span class="line">                            // 初始化加载数量</span><br><span class="line">                            .setInitialLoadSizeHint(PAGE_SIZE)</span><br><span class="line">                            .build()</span><br><span class="line">                    ).build()</span><br><span class="line">    return list</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######5). 创建RecycleView适配器<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Student适配器</span><br><span class="line"> * Created by mazaiting on 2018/7/26.</span><br><span class="line"> */</span><br><span class="line">class StudentAdapter : PagedListAdapter&lt;StudentRoom, StudentAdapter.StudentViewHolder&gt;(DIFF_CALLBACK) &#123;</span><br><span class="line">  override fun onBindViewHolder(holder: StudentViewHolder, position: Int) =</span><br><span class="line">          holder.bindTo(getItem(position))</span><br><span class="line">  </span><br><span class="line">  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder =</span><br><span class="line">          StudentViewHolder(parent)</span><br><span class="line">    </span><br><span class="line">  companion object &#123;</span><br><span class="line">    // Item回调</span><br><span class="line">    private val DIFF_CALLBACK = object : DiffUtil.ItemCallback&lt;StudentRoom&gt;() &#123;</span><br><span class="line">      // 条目是否相同</span><br><span class="line">      override fun areItemsTheSame(oldItem: StudentRoom, newItem: StudentRoom): Boolean = oldItem.id == newItem.id</span><br><span class="line">      // 内容是否相同</span><br><span class="line">      override fun areContentsTheSame(oldItem: StudentRoom, newItem: StudentRoom): Boolean = oldItem == newItem</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  class StudentViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(</span><br><span class="line">          // 加载布局</span><br><span class="line">          LayoutInflater.from(parent.context).inflate(R.layout.item_student, parent, false)</span><br><span class="line">  ) &#123;</span><br><span class="line">    // 查找view</span><br><span class="line">    private val nameView = itemView.findViewById&lt;TextView&gt;(R.id.tv_name)</span><br><span class="line">    // 创建数据</span><br><span class="line">    private var student: StudentRoom? = null</span><br><span class="line">  </span><br><span class="line">    /**</span><br><span class="line">     * 绑定数据</span><br><span class="line">     */</span><br><span class="line">    fun bindTo(student: StudentRoom?) &#123;</span><br><span class="line">      this.student = student</span><br><span class="line">      // 设置文本</span><br><span class="line">      nameView.text = student?.name</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######6). Activity代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">class PagingRoomActivity : AppCompatActivity() &#123;</span><br><span class="line">  /**</span><br><span class="line">   * 懒加载ViewModel</span><br><span class="line">   */</span><br><span class="line">  private val viewModel by lazy &#123;</span><br><span class="line">    ViewModelProviders.of(this).get(StudentViewModel::class.java)</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  override fun onCreate(savedInstanceState: Bundle?) &#123;</span><br><span class="line">    super.onCreate(savedInstanceState)</span><br><span class="line">    setContentView(R.layout.activity_paging_room)</span><br><span class="line">    // 创建适配器</span><br><span class="line">    val adapter = StudentAdapter()</span><br><span class="line">    // 设置布局管理者</span><br><span class="line">    rv_show.layoutManager = LinearLayoutManager(this)</span><br><span class="line">    // 设置适配器</span><br><span class="line">    rv_show.adapter = adapter</span><br><span class="line">    // 数据变化时更新列表</span><br><span class="line">    viewModel.findAllStudents(application).observe(this, Observer &#123; adapter.submitList(it) &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>####3. Pading + 自定义数据源</p>
<p>######1). 创建数据实体类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 数据实体类</span><br><span class="line"> * Created by mazaiting on 2018/7/26.</span><br><span class="line"> */</span><br><span class="line">data class Student (</span><br><span class="line">     val id: Int,</span><br><span class="line">     val name: String</span><br><span class="line">)</span><br><span class="line">``` </span><br><span class="line">######2). 创建适配器</span><br></pre></td></tr></table></figure></p>
<p>/**</p>
<ul>
<li>适配器</li>
<li><p>Created by mazaiting on 2018/7/26.<br>*/<br>class StudentAdapter : PagedListAdapter&lt;Student, StudentAdapter.StudentViewHolder&gt;(DIFF_CALLBACK) {<br>override fun onBindViewHolder(holder: StudentViewHolder, position: Int) =</p>
<pre><code>holder.bindTo(getItem(position))
</code></pre><p>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder =</p>
<pre><code>StudentViewHolder(parent)
</code></pre><p>companion object {<br> /**</p>
<ul>
<li><p>条目不同回调<br>*/<br>private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<student>() {<br>override fun areItemsTheSame(oldItem: Student, newItem: Student): Boolean = oldItem.id == newItem.id</student></p>
<p>override fun areContentsTheSame(oldItem: Student, newItem: Student): Boolean = oldItem == newItem<br>}<br>}</p>
</li>
</ul>
<p>class StudentViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(</p>
<pre><code>// 加载布局
LayoutInflater.from(parent.context).inflate(R.layout.item_student, parent, false)
</code></pre><p>) {<br> // 获取view<br> private val nameView = itemView.findViewById<textview>(R.id.tv_name)<br> private var student: Student? = null</textview></p>
<p> /**</p>
<ul>
<li>绑定数据<br>*/<br>fun bindTo(student: Student?) {<br>this.student = student<br>nameView.text = student?.name<br>}<br>}<br>}<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">######3). 创建数据源</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<p>private val CHEESE_DATA = arrayListOf(<br>        “Abbaye de Belloc”, “Abbaye du Mont des Cats”, “Abertam”, “Abondance”, “Ackawi”,<br>        “Acorn”, “Adelost”, “Affidelice au Chablis”, “Afuega’l Pitu”, “Airag”, “Airedale”,<br>        “Aisy Cendre”, “Allgauer Emmentaler”, “Alverca”, “Ambert”, “American Cheese”,<br>        “Ami du Chambertin”, “Anejo Enchilado”, “Anneau du Vic-Bilh”, “Anthoriro”, “Appenzell”,<br>        “Aragon”, “Ardi Gasna”, “Ardrahan”, “Armenian String”, “Aromes au Gene de Marc”,<br>        “Asadero”, “Asiago”, “Aubisque Pyrenees”, “Autun”, “Avaxtskyr”, “Baby Swiss”,<br>        “Babybel”, “Baguette Laonnaise”, “Bakers”, “Baladi”, “Balaton”, “Bandal”, “Banon”,<br>        “Barry’s Bay Cheddar”, “Basing”, “Basket Cheese”, “Bath Cheese”, “Bavarian Bergkase”,<br>        “Baylough”, “Beaufort”, “Beauvoorde”, “Beenleigh Blue”, “Beer Cheese”, “Bel Paese”,<br>        “Bergader”, “Bergere Bleue”, “Berkswell”, “Beyaz Peynir”, “Bierkase”, “Bishop Kennedy”,<br>        “Blarney”, “Bleu d’Auvergne”, “Bleu de Gex”, “Bleu de Laqueuille”,<br>        “Bleu de Septmoncel”, “Bleu Des Causses”, “Blue”, “Blue Castello”, “Blue Rathgore”,<br>        “Blue Vein (Australian)”, “Blue Vein Cheeses”, “Bocconcini”, “Bocconcini (Australian)”<br>)<br>/**</p>
<ul>
<li>数据源</li>
<li><p>Created by mazaiting on 2018/7/26.<br>*/<br>class StudentDataSource : PositionalDataSource<student>() {<br>/**</student></p>
<ul>
<li>范围加载<br>*/<br>override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<student>) {<br>// 回调结果<br>callback.onResult(loadRangeInternal(params.startPosition, params.loadSize))<br>}</student></li>
</ul>
<p>/**</p>
<ul>
<li>加载初始化<br>*/<br>override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<student>) {<br>// 全部数据数量<br>val totalCount = computeCount()<br>// 当前位置<br>val position = computeInitialLoadPosition(params, totalCount)<br>// 加载数量<br>val loadSize = computeInitialLoadSize(params, position, totalCount)<br>// 回调结果<br>callback.onResult(loadRangeInternal(position, loadSize), position, totalCount)<br>}</student></li>
</ul>
<p>/**</p>
<ul>
<li>加载网络数据<br>*/<br>private fun loadRangeInternal(position: Int, loadSize: Int): MutableList<student> {<br>// 创建列表<br>val list = arrayListOf<student>()<br>// 遍历列表数据<br>CHEESE_DATA.mapIndexed { index, text -&gt; list.add(Student(index, text)) }<br>// 设置加载数据<br>var size = loadSize<br>// 判断加载的位置是否大于总数据<br>if (position &gt;= computeCount()) {<br> // 返回空数据<br> return Collections.emptyList()<br>}<br>// 判断总条数是否大于计算的数据<br>if (position + loadSize &gt; computeCount()) {<br> size = computeCount() - position - 1<br>}<br>//    L.e(“${computeCount()}:: $position :: $size” )<br>// 返回子列表<br>return list.subList(position, size + position)<br>}</student></student></li>
</ul>
<p>/**</p>
<ul>
<li>总条数<br>*/<br>private fun computeCount(): Int = CHEESE_DATA.size</li>
</ul>
</li>
</ul>
<p>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">######4). ViewModel中创建获取数据方法</span><br></pre></td></tr></table></figure></p>
<p>  /**</p>
<ul>
<li>查询本地数据<br>*/<br>fun loadNativeStudent(): LiveData&lt;PagedList<student>&gt; {<br>val dataSourceFactory = DataSource.Factory&lt;Int, Student&gt; { StudentDataSource() }<br>val list: LiveData&lt;PagedList<student>&gt; =<pre><code>LivePagedListBuilder(dataSourceFactory,
        PagedList.Config.Builder()
                .setPageSize(PAGE_SIZE)
                .setEnablePlaceholders(ENABLE_PLACE_HOLDERS)
                .setInitialLoadSizeHint(PAGE_SIZE)
                .build()
).build()
</code></pre>return list<br>}<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">######5). Activity代码</span><br></pre></td></tr></table></figure>
</student></student></li>
</ul>
<p>class PagingCustomActivity : AppCompatActivity() {<br>  /**</p>
<ul>
<li>懒加载ViewModel<br>*/<br>private val viewModel by lazy {<br>ViewModelProviders.of(this).get(StudentViewModel::class.java)<br>}<br>override fun onCreate(savedInstanceState: Bundle?) {<br>super.onCreate(savedInstanceState)<br>setContentView(R.layout.activity_paging_custom)<br>// 创建适配器<br>val adapter = StudentAdapter()<br>// 设置布局管理者<br>rv_show.layoutManager = LinearLayoutManager(this)<br>// 设置适配器<br>rv_show.adapter = adapter<br>// 数据改变通知RecyclerView更新<br>viewModel.loadNativeStudent().observe(this, Observer { adapter.submitList(it) })<br>}<br>}<br><code>`</code></li>
</ul>
<p>######6). <a href="https://developer.android.google.cn/topic/libraries/architecture/paging/" target="_blank" rel="noopener">原文链接</a></p>
<p>######7). <a href="https://gitee.com/mazaiting/Android-Jetpack/tree/master/app/src/main/java/com/mazaiting/jetpack/architecture/paging" target="_blank" rel="noopener">代码下载</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Android-Jetpack/Architecture----Navigation/" rel="next" title="Architecture----Navigation">
                <i class="fa fa-chevron-left"></i> Architecture----Navigation
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Android-Jetpack/Architecture----Room/" rel="prev" title="Architecture----Room">
                Architecture----Room <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
